import os,requests,zipfile,hashlib,struct
from binascii import hexlify as _hexlify, unhexlify
from src.cmdcolor import *
from src.config import *
from colorama import Fore
from tqdm import tqdm
from Crypto.Util import Counter
from Crypto.Cipher import AES
from colorama import Fore

def init():
  if not os.path.isfile(bootori):
      printRed("\n 未检测到boot_ori.dat文件，正在进行下载 \n\n")
      download_file('779653','boot_ori.dat')
  
  if not os.path.isfile(GFXSXOS):
      printRed("\n 未检测到GFX_sxos.exe文件，正在进行下载 \n\n")
      download_file('779644',GFXSXOS)

  if not os.path.exists(dist):
    os.makedirs(dist)

def reverse(a,z) :
    s = ""
    for x in range(-1, -len(a), -2) :
        s += a[x-1] + a[x]
    if (z == 512) :
       if (len(s) != 512) :
           s = '0'+ s
           if (len(s) != 512) :
               s = '0'+ s
               if (len(s) != 512) :
                   s = '0'+ s
    if (z == 64) :
       if (len(s) != 64) :
           s = '0'+ s
           if (len(s) != 64) :
               s = '0'+ s
               if (len(s) != 64) :
                   s = '0'+ s
    return s

def sig_RSA(sig):
    signature = hex(pow(int(_hexlify(sig),16), priv_key, int(pub_key,16)))[2:]
    if (len(signature) != 512) :
        signature = '0'+ signature
        if (len(signature) != 512) :
            signature = '0'+ signature
            if (len(signature) != 512) :
                signature = '0'+ signature
    return signature

def hexlify(b: (bytes, bytearray)) -> str:
    return _hexlify(b).decode("utf8")

def aes_ctr_dec(buf, key, iv):
    hex_val = (iv.hex())
    ctr = Counter.new(128, initial_value=int(hex_val, 16))
    return AES.new(key, AES.MODE_CTR, counter=ctr).encrypt(buf)

def hexxor (a, b):
    s =  ''.join(["%x" % (int(a,16) ^ int(b,16))])
    if (len(s) != 64) :
        s = '0'+ s
        if (len(s) != 64) :
            s = '0'+ s
            if (len(s) != 64) :
                s = '0'+ s
    return s

# 删除文件夹下的所有文件
def del_file(path):
    ls = os.listdir(path)
    for i in ls:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):
            del_file(c_path)
        else:
            os.remove(c_path)

# 下载解压主题文件
def download_file(id, dzip_name):
    with requests.get(base_url+id+'/download', stream=True) as r, open(dzip_name, 'wb') as file:
      # 请求文件的大小单位字节B
      total_size = int(r.headers['content-length'])
      # 以下载的字节大小
      content_size = 0
      # 上秒的下载大小
      temp_size = 0
      # 进度条
      pbar = tqdm(total=total_size, initial=content_size,unit='B', unit_scale=True, desc=dzip_name+': ', bar_format='{l_bar}%s{bar}%s{r_bar}' % (Fore.GREEN, Fore.RESET))
      # 开始下载每次请求1024字节
      for content in r.iter_content(chunk_size=1024):
        file.write(content)
        # 统计以下载大小
        content_size += len(content)
        # 下载进度条
        pbar.update(content_size - temp_size)
        # 重置以下载大小
        temp_size = content_size
      pbar.close()

# 下载解压主题文件
def download_themes(id):
  printYellow("\n 正在下载主题文件，请稍等... \n\n")
  dzip_name = 'themes.zip'
  dcp_name = 'themes'
  download_file(id,dzip_name)
  zip_file = zipfile.ZipFile(dzip_name)
  zip_list = zip_file.namelist()
  for f in zip_list:
     zip_file.extract(f,dcp_name)
  zip_file.close()
  print('\n')
  os.remove(dzip_name)


# 判断版本
def check_boot_v(boot):
  sha256 = hashlib.sha256(boot).hexdigest()
  boot_ver = struct.unpack("II", boot[0x08:0x10])
  # TX BOOT3.1
  if(boot_ver[1] == 0x302E) and (boot_ver[0] == 0x312E3356) and (sha256 == "f05c9c9f1a862ff7ac6ae44fe5bf0bb4749db0b2dc6565f6f0f2acdbe81bb06b"):
    return 310
  else:
    printRed("\n 请使用未修改的SXOS3.1的boot.dat，然后进行重命名boot_ori.dat，或者删除boot_ori.dat，程序会自动进行下载3.1的boot \n\n")
    os.system('pause')
    return sys.exit()

# 主题状态
def get_theme_status(themesId):
  if int(themesId) >= 1 and int(themesId) < 11 :
    if os.path.exists('out'):
        del_file("out")
    if os.path.exists('themes'):
        del_file("themes")
  if themesId == "1":
    download_themes("774728")
  elif themesId == "2":
    download_themes("774697")
  elif themesId == "3":
    download_themes("774733")
  elif themesId == "4":
    download_themes("774731")
  elif themesId == "5":
    download_themes("774736")
  elif themesId == "6":
    download_themes("774734")
  elif themesId == "7":
    download_themes("774730")
  elif themesId == "8":
    download_themes("774735")
  elif themesId == "9":
    download_themes("774729")
  elif themesId == "10":
    download_themes("774737")
  os.system(GFXSXOS)
  if int(themesId) >= 2 and int(themesId) <= 11 :
    return 1
  else:
    return 0

# 创建license证书
def create_license():
  if not os.path.isfile(Request):
    printRed("\n 未检测到license-request.dat文件,将生成通用证书 \n")
    validlic = open(Licence, "wb")
    validlic.write(unhexlify(goodlic))
    validlic.close()
    printDarkGreen("\n 成功创建license证书!!! \n")
  else:
    tmp = open(Request, "rb")
    Request_tmp = tmp.read()
    tmp.close()

    with open(Licence, "wb") as Licence_tmp:
      Licence_tmp.write(unhexlify(padding))
      Licence_tmp.seek(0xE0)
      Licence_tmp.write(Request_tmp[0x0:0x20])
  
    with open(Licence, "rb") as tmp:
      Licence_sig = tmp.read()
    signature = sig_RSA(Licence_sig)
  
    with open(Licence, "wb") as Licence_tmp:
      Licence_tmp.write(unhexlify(signature))
      printDarkGreen("\n 成功创建license证书!!! \n")
